package com.web.java0401redis.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.web.java0401redis.entity.Student;
import com.web.java0401redis.mapper.StudentMapper;
import com.web.java0401redis.service.StudentService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
@CacheConfig(cacheNames = "student")
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

//    public static final String PREFIX = "student-";
//    @Resource
//    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private StudentMapper studentMapper;

    @Cacheable(key = "T(String).valueOf(#id)")
    @Override
    public Student findStudentById(Integer id) {
        return studentMapper.selectById(id);
    }

    @CacheEvict(key = "T(String).valueOf(#id)")
    @Override
    public void deleteStudent(Integer id) {
        studentMapper.deleteById(id);
    }

    @CachePut(key = "T(String).valueOf(#student.id)")
    @Override
    public Student addStudent(Student student) {
        studentMapper.insert(student);
        return student;
    }

    @CachePut(key = "T(String).valueOf(#student.id)")
    @Override
    public Student updateStudent(Student student) {
        studentMapper.updateById(student);
        return student;
    }

//    @Override
//    synchronized public Student findStudentById(Integer id) {
//        //获得string类型的操作对象
//        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
//        //查询redis
//        Student stu = (Student) ops.get(PREFIX + id);
//        //判断redis如果存在数据，就直接返回
//        if(stu != null){
//            log.info("redis存在数据，返回" + stu);
//            return stu;
//        }
//        log.info("redis不存在数据，查询数据库");
//        try {
//            Thread.sleep(100);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        //redis如果没有，再查询数据库
//        stu = studentMapper.selectById(id);
//        //如果数据库有数据，就保存到redis中，返回数据
//        if(stu != null){
//            log.info("数据库存在数据，保存到redis中，返回" + stu);
//            ops.set(PREFIX + id,stu);
//            return stu;
//        }
//        //如果数据库没有，就返回空数据
//        log.info("数据库查不到，返回空");
//        ops.set(PREFIX + id,new Student(),5, TimeUnit.SECONDS);
//        return null;
//    }
}
